//
//  insertUserIDView.swift
//  压岁_IOS
//
//  Created by 梓简王 on 2017/7/18.
//  Copyright © 2017年 梓简王. All rights reserved.
//

import Foundation
import QorumLogs
import TextFieldEffects
import Alamofire
protocol insertUserIDDelegate{
    func checkSuccessAction()
}

class insertUserIDView: UIView,UITextFieldDelegate {
    var selfFrame:CGRect?
    //验证手机号码界面控件
    var userTelTextView: AkiraTextField?
    var userCheckNo: AkiraTextField?
    var sendButton: UIButton!
    var countdownTimer: NSTimer?
    var delegate:insertUserIDDelegate?
    var confirmBtn:UIButton?
    
    //计数器，倒计时60s的计算
    var remainingSeconds: Int = 0 {
        willSet {
            sendButton.setTitle("\(newValue)  S", forState: .Normal)
            
            if newValue <= 0 {
                sendButton.setTitle("重新获取", forState: .Normal)
                isCounting = false
            }
        }
    }
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTime:", userInfo: nil, repeats: true)
                
                remainingSeconds = 60
                
                sendButton.backgroundColor = UIColor.grayColor()
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                
                sendButton.backgroundColor = UIColor.redColor()
            }
            
            sendButton.enabled = !newValue
        }
    }
    //手机号码确认界面控件位置
    var userPhoneFrame:CGRect?
    var userCheckNoFrame:CGRect?
    var sendBtnCenter:CGPoint?
    var confirmFrame:CGRect?
    var confirmCenter:CGPoint?
    
    var role:String?
//    let userPhoneFrame = CGRect(x: 23, y: 225, width: commonVariable.SYSTEM_WIDTH - 46, height: 60)//输入手机号码位置
//    let userCheckNoFrame = CGRect(x: 23, y: 285, width: commonVariable.SYSTEM_WIDTH - 173, height: 60)//输入验证码位置
//    
//    let sendBtnCenter = CGPoint(x: UIScreen.mainScreen().bounds.width - 86, y: 325)//点击验证位置
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    init(frame: CGRect,role:String) {
        super.init(frame: frame)
        self.role = role
        selfFrame = frame
        initUI()
    }
    
    func initUI(){
        //初始化控件
        self.backgroundColor = UIColor.whiteColor()
        self.layer.cornerRadius = 5
        self.clipsToBounds = true
        //初始化控件位置
        userPhoneFrame = CGRect(x: 23, y: 23, width: Int((self.selfFrame?.width)!) - 46, height: 60)
        userCheckNoFrame = CGRect(x: 23, y: 83, width: Int((userPhoneFrame?.width)!) - 87, height: 60)
        sendBtnCenter = CGPoint(x: selfFrame!.width - 66, y: 120)
        //创建手机验证界面对应控件
        self.userTelTextView = AkiraTextField(frame: self.userPhoneFrame!)
        self.userTelTextView?.borderColor = commonVariable.IRONCOLOR
        self.userTelTextView?.placeholderColor = commonVariable.IRONCOLOR
        self.userTelTextView?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.userTelTextView?.placeholder = "请输入\(role!)角色的手机"
        
        self.userCheckNo = AkiraTextField(frame: userCheckNoFrame!)
        self.userCheckNo?.borderColor = commonVariable.IRONCOLOR
        self.userCheckNo?.placeholderColor = commonVariable.IRONCOLOR
        self.userCheckNo?.font = UIFont(name: commonVariable.CHINAFONTNAME, size: 20)
        self.userCheckNo?.placeholder = "请输入验证码"
        
        self.userTelTextView?.delegate = self
        self.userCheckNo?.delegate = self
        
        self.userTelTextView?.inputView = commonVariable.NUMPAD
        self.userCheckNo?.inputView = commonVariable.NUMPAD
        
        //初始化获取验证码选项
        sendButton = UIButton()
        sendButton.frame = CGRect(x: 0, y: 0, width: 67, height: 40)
        sendButton.center = sendBtnCenter!
        sendButton.backgroundColor = commonVariable.DEEPREDCOLOR
        sendButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        sendButton.setTitle("获取验证码", forState: .Normal)
        sendButton.titleLabel?.font = UIFont.init(name: commonVariable.CHINAFONTNAME, size: 11)
        sendButton.addTarget(self, action: "sendButtonClick:", forControlEvents: .TouchUpInside)
        self.confirmFrame = CGRect(x: 0, y: 0, width: 100, height: 35)
        self.confirmCenter = CGPoint(x: (selfFrame?.width)!/2, y: 163.0)
        //创建确认按钮
        self.confirmBtn = commonTool.initLoginBtn("绑 定", rect: confirmFrame!, center: confirmCenter!)
        self.confirmBtn?.addTarget(self, action: "checkThePhone", forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(self.confirmBtn!)
        self.addSubview(userTelTextView!)
        self.addSubview(userCheckNo!)
        self.addSubview(sendButton)
    }
    //MARK: - 获取验证码方法
    func sendButtonClick(sender: UIButton) {
        //下面获取验证码
        if (self.userTelTextView!.text == "" ) {
            SweetAlert().showAlert("宝贝~", subTitle: "请输入您的手机号码！", style: AlertStyle.Warning)
        }else{
            self.isCounting = true
            let telNo = self.userTelTextView!.text as! NSString
            SMSSDK.getVerificationCodeByMethod(SMSGetCodeMethodSMS, phoneNumber: telNo as String, zone: "86", result: { (error:NSError!) -> Void in
                if(error == nil){
                    QL2("发送成功")
                }else {
                    self.isCounting = false
                    switch error.code {
                    case 457:
                        SweetAlert().showAlert("宝贝~", subTitle: "您输入的号码有误！", style: AlertStyle.Warning)
                    case 477:
                        SweetAlert().showAlert("宝贝~", subTitle: "对不起，当前手机号码今日发送过多，请明日再尝试！", style: AlertStyle.Warning)
                    default :
                        SweetAlert().showAlert("宝贝~", subTitle: "出现未知错误！", style: AlertStyle.Warning)
                    }
                    QL2("发送失败")
                }
            })
        }
    }
    //验证手机与验证码
    func checkThePhone(){
        //下面进行验证
        let telNo = self.userTelTextView!.text
        let checkNo = self.userCheckNo!.text
        if checkNo == "" {
            SweetAlert().showAlert("宝贝~", subTitle: "请输入验证码！", style: AlertStyle.Warning)
        }else{
            SMSSDK.commitVerificationCode(checkNo, phoneNumber: telNo, zone: "86", result: { (error:NSError!) -> Void in
                if error == nil {
                    //验证成功
                    //Mark :-绑定行为
                    var url = ""
                    switch(self.role!){
                    case "0":
                        url = commonVariable.BOUNDFATHERACCOUNT
                        break
                    case "1":
                        url = commonVariable.BOUNDMOTHERACCOUNT
                        break
                    case "2":
                        url = commonVariable.BOUNDKIDACCOUNT
                        break
                    default:
                        break
                    }
                    let body = ["userID":"\((commonVariable.LOCAL_USER?.id)!)","userRole":"\((commonVariable.LOCAL_USER?.commonRoleType)!)","userTel":"\((self.userTelTextView?.text)!)"]
                    Alamofire.request(.POST, url,parameters:body,headers:nil).responseJSON() {
                        response in
                        guard let JSONDIC = response.result.value else {
                            QL4(response.result.error)
                            switch response.result.error!.code {
                            case -1009 :
                                SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                            case 3840:
                                SweetAlert().showAlert("对不起", subTitle: "服务出现故障，请联系管理员", style: AlertStyle.Error)
                            case -1001 :
                                
                                SweetAlert().showAlert("对不起", subTitle: "上传信息超时", style: AlertStyle.Error)
                            default:
                                SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                            }
                            return }
                        QL2(JSONDIC)
                        let resultDict = JSONDIC as? NSDictionary
                        let jsonObj = JSON(JSONDIC)
                        let errorCode = jsonObj["errorcode"].intValue
                        let errorMsg = jsonObj["message"].stringValue
                        QL2(errorMsg)
                        if errorCode != 1 {
                            SweetAlert().showAlert("对不起", subTitle: "\(errorMsg)", style: AlertStyle.Warning)
                        }else{
                            self.delegate?.checkSuccessAction()
                        }
                    }
                }else{
                    SweetAlert().showAlert("宝贝~", subTitle: "你输入的验证码有小瑕疵哦~", style: AlertStyle.Error)
                }
            })
        }
    }
    //MARK: -textfield代理实现
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    func updateTime(timer: NSTimer) {
        remainingSeconds -= 1
    }
}